package leetcode.editor.cn;

import java.util.*;
import leetcode.editor.common.*;

public class GroupAnagrams {

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {

            // 异分词   ： 单词中的字母 排序后 相同
            // 也可统计 出每个单词中字母出现的次数  ， 如果 相同  则属于一个异分词

            HashMap<String, List<String>> groupMap = new HashMap<>();
            for(String str : strs){
                String key = getWordKey(str);
                final List<String> stringList = groupMap.getOrDefault(key, new ArrayList<>());
                stringList.add(str);
                groupMap.put(key, stringList);
            }
            return new ArrayList<>(groupMap.values());
        }



        // 记录 每个单词中字母出现的次数
        public String getWordKey(String str){
            final int[] words = new int[52];
             Arrays.fill(words, 0);
            final char[] charArray = str.toCharArray();
            for (char c : charArray) {
                if (c >= 'a' && c <= 'z') {
                    words[c - 'a']++;
                } else {
                    words[c - 'A' + 26]++;
                }
            }
            return new String(words, 0, words.length);
        }


    }
    //leetcode submit region end(Prohibit modification and deletion)

    
    public static void main(String[] args) {
        Solution solution = new GroupAnagrams().new Solution();
        // put your test code here
        solution.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}).forEach(System.out::println);
    }
}
